using System;
using System.Data;
using System.Xml;
using System.Web;
using System.Collections.Generic;
using Samples.ShoppingCart;

/// <summary>
/// Summary description for BusinessLayer
/// </summary>
public class BusinessLayer
{
    private static XmlDocument GetDocument()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/BookCatalog.xml"));

        return doc;
    }

    private static Book PopulateBook(XmlNode bookNode)
    {
        Book book = new Book();
        book.Id = bookNode["id"].InnerText;
        book.Title = bookNode["title"].InnerText;
        book.Description = book.Title;
        book.ImageUrl = bookNode["imageUrl"].InnerText;

        return book;
    }

    public static List<Book> GetBooks()
    {
        XmlDocument doc = GetDocument();

        List<Book> books = new List<Book>();
        XmlNodeList bookNodes = doc.SelectNodes("books/book");

        foreach (XmlNode node in bookNodes)
        {
            Book book = PopulateBook(node);
            books.Add(book);
        }

        return books;
    }

    public static Book GetBookById(string id)
    {
        XmlDocument doc = GetDocument();

        XmlNode bookNode = doc.SelectSingleNode(String.Format("books/book[id='{0}']", id));

        if (bookNode == null) return null;

        Book book = PopulateBook(bookNode);
        
        return book;
    }
}
